package com.domi.log;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Map;
import java.util.Objects;
import java.util.StringJoiner;

@Slf4j
@Component
public class LoggerInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HandlerMethod controller = (HandlerMethod) handler;
        log.info("---> {} {}", request.getMethod(), request.getRequestURL());
        log.info("{}", this.getHandlerDescription(controller.getBeanType(), controller.getMethod()));
        String contentType = request.getContentType();
        if (!Objects.isNull(contentType)) {
            log.info("Content-Type: {}", contentType);
            log.info("Content-Length: {}", request.getContentLength());
        }
        Map<String, String[]> parameterMap = request.getParameterMap();
        if (!Objects.isNull(parameterMap)) {
            parameterMap.keySet().stream()
                    .map(s -> s + "=" + (s.length() > 1 ? Arrays.toString(parameterMap.get(s)) : parameterMap.get(s)[0]))
                    .forEach(s -> log.info("{}", s));
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("<--- HTTP STATUS: {}", response.getStatus());
        String contentType = response.getContentType();
        if (!Objects.isNull(contentType)) {
            log.info("Content-Type: {}", contentType);
            log.info("Content-Length: {}", request.getContentLength());
        }
    }

    private String getHandlerDescription(Class<?> beanType, Method method) {
        StringJoiner joiner = new StringJoiner(", ", "(", ")");
        for (Class<?> paramType : method.getParameterTypes()) {
            joiner.add(paramType.getSimpleName());
        }
        return beanType.getSimpleName() + "#" + method.getName() + joiner;
    }

}